package com.kexio.security.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kexio.common.dto.PageRequest;
import com.kexio.security.domain.User;
import com.kexio.security.dto.UserRequest;
import com.kexio.security.service.UserRepository;
import com.kexio.security.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户数据访问实现类
 * 
 * @author kexio
 */
@Repository
public class UserRepositoryImpl implements UserRepository {

    private static final Logger log = LoggerFactory.getLogger(UserRepositoryImpl.class);

    private final UserMapper userMapper;

    public UserRepositoryImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User save(User user) {
        if (user.getId() == null) {
            // 新增用户
            user.setCreatedTime(LocalDateTime.now());
            user.setUpdatedTime(LocalDateTime.now());
            userMapper.insert(user);
            log.debug("用户新增成功: {}", user.getUsername());
        } else {
            // 更新用户
            user.setUpdatedTime(LocalDateTime.now());
            userMapper.updateById(user);
            log.debug("用户更新成功: {}", user.getUsername());
        }
        return user;
    }

    @Override
    public Optional<User> findById(Long id) {
        User user = userMapper.selectById(id);
        return Optional.ofNullable(user);
    }

    @Override
    public Optional<User> findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        return Optional.ofNullable(user);
    }

    @Override
    public Optional<User> findByEmail(String email) {
        User user = userMapper.findByEmail(email);
        return Optional.ofNullable(user);
    }

    @Override
    public Optional<User> findByPhone(String phone) {
        User user = userMapper.findByPhone(phone);
        return Optional.ofNullable(user);
    }

    @Override
    public boolean existsByUsername(String username, Long excludeId) {
        long count = userMapper.countByUsername(username, excludeId);
        return count > 0;
    }

    @Override
    public boolean existsByEmail(String email, Long excludeId) {
        long count = userMapper.countByEmail(email, excludeId);
        return count > 0;
    }

    @Override
    public boolean existsByPhone(String phone, Long excludeId) {
        long count = userMapper.countByPhone(phone, excludeId);
        return count > 0;
    }

    @Override
    public com.kexio.common.dto.PageResponse<User> findPage(UserRequest request, PageRequest pageRequest) {
        // 创建MyBatis-Plus分页对象
        Page<User> mpPage = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        
        // 执行分页查询
        IPage<User> result = userMapper.selectUserPage(mpPage, request);
        
        // 转换为通用分页对象
        com.kexio.common.dto.PageResponse<User> pageResponse = new com.kexio.common.dto.PageResponse<>(
            result.getRecords(),
            (int) result.getCurrent(),
            (int) result.getSize(),
            result.getTotal()
        );
        
        log.debug("分页查询用户完成，共{}条记录", result.getTotal());
        return pageResponse;
    }

    @Override
    public List<User> findByDeptId(Long deptId) {
        return userMapper.selectByDeptId(deptId);
    }

    @Override
    public List<User> findByRoleId(Long roleId) {
        return userMapper.selectByRoleId(roleId);
    }

    @Override
    public List<User> findByStatus(Integer status) {
        return userMapper.selectByStatus(status);
    }

    @Override
    public int updateLastLoginInfo(Long id, LocalDateTime lastLoginTime, String lastLoginIp, Integer loginCount) {
        int rows = userMapper.updateLastLoginInfo(id, lastLoginTime, lastLoginIp, loginCount);
        log.debug("更新用户{}登录信息，影响{}行", id, rows);
        return rows;
    }

    @Override
    public int deleteById(Long id) {
        int rows = userMapper.deleteById(id);
        log.debug("删除用户{}，影响{}行", id, rows);
        return rows;
    }

    @Override
    public int deleteByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        int rows = userMapper.deleteByIds(ids);
        log.debug("批量删除用户{}个，影响{}行", ids.size(), rows);
        return rows;
    }

    @Override
    public long count() {
        Long count = userMapper.selectCount(null);
        return count != null ? count : 0L;
    }

    @Override
    public long countByRequest(UserRequest request) {
        return userMapper.countByRequest(request);
    }
}
